package com.csdj.server.config;

import com.csdj.server.pojo.Menu;
import com.csdj.server.pojo.Role;
import com.csdj.server.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

/**
 * @ClassName: CustomFilter
 * @Author: ZouLi
 * @Description: 用户过滤器
 * @Date: 2022/12/23 10:47
 **/
@Component
public class CustomFilter implements FilterInvocationSecurityMetadataSource {
    // 注入service
    @Autowired
    private IMenuService menuServiceImpl;
    // 地址匹配实例
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        // 获取当前请求地址
        String requestUrl = ((FilterInvocation) object).getRequestUrl();
        // 获取全部菜单
        List<Menu> menus = menuServiceImpl.getMenusWithRole();
        // 遍历菜单
        for (Menu item : menus) {
            // 根据请求判断菜单
            if (antPathMatcher.match(item.getUrl(),requestUrl)) {
                // 匹配成功 则获取
                // 遍历角色信息 .map：筛选。成立新的集合。再转成String数组
                String[] roleName = item.getRoles().stream().map(Role::getName).toArray(String[]::new);
                return SecurityConfig.createList(roleName);
            }
        }
        //没匹配的url默认为登录即可访问
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return false;
    }
}
